{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "eb32f974",
      "metadata": {},
      "source": [
        "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/mongodb-developer/GenAI-Showcase/blob/main/notebooks/evals/voyageai-embeddings-eval.ipynb)\n",
        "\n",
        "[![View Article](https://img.shields.io/badge/View%20Article-blue)](https://www.mongodb.com/company/blog/technical/how-choose-best-embedding-model-for-your-llm-application/?utm_campaign=devrel&utm_source=cross-post&utm_medium=organic_social&utm_content=https%3A%2F%2Fgithub.com%2Fmongodb-developer%2FGenAI-Showcase&utm_term=apoorva.joshi)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "39b4d49e-31a1-4093-9255-9cb8e6f96b0d",
      "metadata": {
        "tags": []
      },
      "source": [
        "# How to choose the right embedding model for your RAG application\n",
        "\n",
        "This notebook evaluates the [voyage-3-large](https://docs.voyageai.com/embeddings/) model.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f3a115b9-68e5-44f7-9ea7-fff56bc9ee59",
      "metadata": {},
      "source": [
        "## Step 1: Install required libraries\n",
        "\n",
        "- **datasets**: Python library to get access to datasets available on Hugging Face Hub\n",
        "- **voyageai**: Python library to interact with Voyage AI's APIs\n",
        "- **numpy**: Python library that provides tools to perform mathematical operations on arrays\n",
        "- **pandas**: Python library for data analysis, exploration and manipulation\n",
        "- **tdqm**: Python module to show a progress bar for loops\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 27,
      "id": "a999fe13-3eee-4fd8-a9fd-0f2f37171ed3",
      "metadata": {
        "tags": []
      },
      "outputs": [],
      "source": [
        "! pip install -qU datasets voyageai numpy pandas tqdm"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "87bd8b3e-984b-4dff-bd7f-615e577a9ef8",
      "metadata": {},
      "source": [
        "## Step 2: Setup pre-requisites\n",
        "\n",
        "Set the Voyage API key as an environment variable, and initialize the Voyage AI client.\n",
        "\n",
        "Steps to obtain a Voyage AI API Key can be found [here](https://docs.voyageai.com/docs/api-key-and-installation#authentication-with-api-keys).\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 28,
      "id": "f62e40d3-852c-4abf-9151-875a1d32e93e",
      "metadata": {},
      "outputs": [],
      "source": [
        "import getpass\n",
        "import os\n",
        "\n",
        "import voyageai"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 29,
      "id": "a8e8bcde-c242-4641-a7c8-5f69c60d021e",
      "metadata": {},
      "outputs": [
        {
          "name": "stdin",
          "output_type": "stream",
          "text": [
            "Voyage API Key: ········\n"
          ]
        }
      ],
      "source": [
        "os.environ[\"VOYAGE_API_KEY\"] = getpass.getpass(\"Voyage API Key:\")\n",
        "voyage_client = voyageai.Client()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b5a99a68-a7d2-4657-8f05-ea75f19b6748",
      "metadata": {},
      "source": [
        "## Step 3: Download the evaluation dataset\n",
        "\n",
        "We will use MongoDB's [cosmopedia-wikihow-chunked](https://huggingface.co/datasets/MongoDB/cosmopedia-wikihow-chunked) dataset, which has chunked versions of WikiHow articles from the [Cosmopedia](https://huggingface.co/datasets/HuggingFaceTB/cosmopedia) dataset released by Hugging Face. The dataset is pretty large, so we will only grab the first 2k records for testing.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 30,
      "id": "7862e2db-fec8-4294-ad75-9753e69adc1a",
      "metadata": {},
      "outputs": [],
      "source": [
        "import pandas as pd\n",
        "from datasets import load_dataset\n",
        "\n",
        "# Use streaming=True to load the dataset without downloading it fully\n",
        "data = load_dataset(\"MongoDB/cosmopedia-wikihow-chunked\", split=\"train\", streaming=True)\n",
        "# Get first 2k records from the dataset\n",
        "data_head = data.take(2000)\n",
        "df = pd.DataFrame(data_head)\n",
        "\n",
        "# Use this if you want the full dataset\n",
        "# data = load_dataset(\"AIatMongoDB/cosmopedia-wikihow-chunked\", split=\"train\")\n",
        "# df = pd.DataFrame(data)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "70d329bc-cdb7-4651-bef0-8d2ae09d9e4b",
      "metadata": {},
      "source": [
        "## Step 4: Data analysis\n",
        "\n",
        "Make sure the length of the dataset is what we expect (2k), preview the data, drop Nones etc.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 31,
      "id": "39c0f32d-c6f7-4faa-92e1-fae25e9eb2ba",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "2000"
            ]
          },
          "execution_count": 31,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Ensuring length of dataset is what we expect i.e. 2k\n",
        "len(df)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 32,
      "id": "6782ab49-3d9d-4f67-8b33-474f02b7e993",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/html": [
              "<div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>doc_id</th>\n",
              "      <th>chunk_id</th>\n",
              "      <th>text_token_length</th>\n",
              "      <th>text</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>180</td>\n",
              "      <td>Title: How to Create and Maintain a Compost Pi...</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>141</td>\n",
              "      <td>**Step 2: Gather Materials**\\nGather brown (ca...</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>2</th>\n",
              "      <td>0</td>\n",
              "      <td>2</td>\n",
              "      <td>182</td>\n",
              "      <td>_Key guideline:_ For every volume of green mat...</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>3</th>\n",
              "      <td>0</td>\n",
              "      <td>3</td>\n",
              "      <td>188</td>\n",
              "      <td>_Key tip:_ Chop large items like branches and ...</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>4</th>\n",
              "      <td>0</td>\n",
              "      <td>4</td>\n",
              "      <td>157</td>\n",
              "      <td>**Step 7: Maturation and Use**\\nAfter 3-4 mont...</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>"
            ],
            "text/plain": [
              "   doc_id  chunk_id  text_token_length  \\\n",
              "0       0         0                180   \n",
              "1       0         1                141   \n",
              "2       0         2                182   \n",
              "3       0         3                188   \n",
              "4       0         4                157   \n",
              "\n",
              "                                                text  \n",
              "0  Title: How to Create and Maintain a Compost Pi...  \n",
              "1  **Step 2: Gather Materials**\\nGather brown (ca...  \n",
              "2  _Key guideline:_ For every volume of green mat...  \n",
              "3  _Key tip:_ Chop large items like branches and ...  \n",
              "4  **Step 7: Maturation and Use**\\nAfter 3-4 mont...  "
            ]
          },
          "execution_count": 32,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Previewing the contents of the data\n",
        "df.head()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 33,
      "id": "04563eaf-bbd8-4969-9671-eb5312817402",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Only keep records where the text field is not null\n",
        "df = df[df[\"text\"].notna()]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 34,
      "id": "cd5a91c3-2f68-4157-a747-05bbc934d53a",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "352"
            ]
          },
          "execution_count": 34,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Number of unique documents in the dataset\n",
        "df.doc_id.nunique()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0400259f-65ca-4301-a245-7af0b746abf1",
      "metadata": {},
      "source": [
        "## Step 5: Creating embeddings\n",
        "\n",
        "Define the embedding function, and run a quick test.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 35,
      "id": "3d936743-f18b-410e-8397-c0acf9c61a5e",
      "metadata": {},
      "outputs": [],
      "source": [
        "from typing import List"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 36,
      "id": "bda20d74-7296-40df-ab19-ea63a5b47e6d",
      "metadata": {},
      "outputs": [],
      "source": [
        "def get_embeddings(text: str, input_type: str) -> List[float]:\n",
        "    \"\"\"\n",
        "    Get embeddings using the Voyage AI API.\n",
        "\n",
        "    Args:\n",
        "        text (str): Text to embed\n",
        "        input_type (str): Type of input to embed. Can be \"document\" or \"query\".\n",
        "\n",
        "    Returns:\n",
        "        List[float]: Embedding vector\n",
        "    \"\"\"\n",
        "    response = voyage_client.embed(text, model=\"voyage-3-large\", input_type=input_type)\n",
        "    return response.embeddings[0]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 37,
      "id": "0da5f1da-f4bd-4551-871e-350d44ed0d31",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Generating a test embedding\n",
        "test_voyageai_embed = get_embeddings(df.iloc[0][\"text\"], \"document\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 38,
      "id": "a3f8cd22-d3e7-45cb-abe1-4993208f1391",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "1024"
            ]
          },
          "execution_count": 38,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Sanity check to make sure embedding dimensions are as expected i.e. 1024\n",
        "len(test_voyageai_embed)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "17d7c15a-8d3e-4680-acf1-a61a5be5c998",
      "metadata": {},
      "source": [
        "## Step 6: Evaluation\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "62b14e37",
      "metadata": {},
      "source": [
        "### Measuring embedding latency\n",
        "\n",
        "Create a local vector store (list) of embeddings for the entire dataset.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 39,
      "id": "76e0e043-dea1-4fb7-a779-6aeba0c690e4",
      "metadata": {},
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "from tqdm.auto import tqdm"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 40,
      "id": "9e0c475e-8f36-4183-997f-c13b2320b280",
      "metadata": {},
      "outputs": [],
      "source": [
        "texts = df[\"text\"].tolist()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 41,
      "id": "501dc5a1-daed-4ae9-a246-b388b0698e22",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "application/vnd.jupyter.widget-view+json": {
              "model_id": "31d83f5c907648d3852615cb3c7f0da9",
              "version_major": 2,
              "version_minor": 0
            },
            "text/plain": [
              "  0%|          | 0/2000 [00:00<?, ?it/s]"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "embeddings = []\n",
        "# Generate embeddings\n",
        "for text in tqdm(texts):\n",
        "    embedding = get_embeddings(text, \"document\")\n",
        "    # Add to the list of embeddings\n",
        "    embeddings.append(np.array(embedding))"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3918f00e-b31f-4225-80fd-1761fbf3a3d2",
      "metadata": {},
      "source": [
        "### Measuring retrieval quality\n",
        "\n",
        "- Create embedding for the user query\n",
        "- Get the top 5 most similar documents from the local vector store using cosine similarity as the similarity metric\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 18,
      "id": "7fa4806b-7311-4516-aea2-a71230c4f571",
      "metadata": {},
      "outputs": [],
      "source": [
        "from sentence_transformers.util import cos_sim"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 19,
      "id": "ff11c827-5e24-481b-af48-8389b9963bda",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Converting embeddings list to a Numpy array- required to calculate cosine similarity\n",
        "embeddings = np.asarray(embeddings)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 20,
      "id": "f9d9c773-896b-4098-8234-fe77360820c9",
      "metadata": {},
      "outputs": [],
      "source": [
        "def query(query: str, top_k: int = 3) -> None:\n",
        "    \"\"\"\n",
        "    Query the local vector store for the top 3 most relevant documents.\n",
        "\n",
        "    Args:\n",
        "        query (str): User query\n",
        "        top_k (int, optional): Number of documents to return. Defaults to 3.\n",
        "    \"\"\"\n",
        "    # Generate embedding for the user query\n",
        "    query_emb = np.asarray(get_embeddings(query, \"query\"))\n",
        "    # Calculate cosine similarity\n",
        "    scores = cos_sim(query_emb, embeddings)[0]\n",
        "    # Get indices of the top k records\n",
        "    idxs = np.argsort(-scores)[:top_k]\n",
        "\n",
        "    print(f\"Query: {query}\")\n",
        "    for idx in idxs:\n",
        "        print(f\"Score: {scores[idx]:.4f}\")\n",
        "        print(texts[idx])\n",
        "        print(\"--------\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 21,
      "id": "ed8ad9ef-67ad-454d-8fa7-65b1e4a35e03",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Query: Give me some tips to improve my mental health.\n",
            "Score: 0.7262\n",
            "Step 2: Reach Out to Someone Trustworthy\n",
            "Connect with someone who cares about you—a friend, family member, mental health professional, or support group. Talking openly about your struggles can lighten your emotional burden, making it easier to manage. Sharing your feelings may also lead to helpful suggestions and advice from others.\n",
            "\n",
            "Guideline: Make sure to choose someone trustworthy who has shown empathy towards you before. If possible, reach out to more than one person to build a strong support network around you.\n",
            "\n",
            "Step 3: Engage in Physical Activity\n",
            "Exercise releases endorphins, which improve mood and reduce stress levels. Go for a walk, jog, bike ride, swim, or engage in any physical activity that suits your abilities. Exercising regularly can significantly impact overall wellbeing by reducing symptoms of depression and anxiety.\n",
            "\n",
            "Key Tip: Start small - aim for just five minutes of exercise if needed, then gradually increase duration over time. The most important thing is to get started!\n",
            "--------\n",
            "Score: 0.7074\n",
            "Key Tips & Guidelines:\n",
            "\n",
            "* Confide in people who genuinely care about your wellbeing\n",
            "* Attend meetings regularly to reinforce positive behaviors\n",
            "\n",
            "Step 8: Practice Mindfulness\n",
            "Incorporate mindfulness techniques into your daily routine through meditation, deep breathing exercises, or progressive muscle relaxation. These practices enhance self-awareness, emotional regulation, and stress management skills, promoting healthier coping mechanisms.\n",
            "\n",
            "Key Tips & Guidelines:\n",
            "\n",
            "* Dedicate at least 10 minutes per day to mindfulness activities\n",
            "* Explore different methods to find what works best for you\n",
            "\n",
            "Step 9: Prioritize Self-Care\n",
            "Attend to physical, emotional, and psychological needs by maintaining a nutritious diet, getting sufficient sleep, and exercising regularly. Adequate self-care strengthens resilience against relapse and improves overall quality of life.\n",
            "\n",
            "Key Tips & Guidelines:\n",
            "\n",
            "* Develop a consistent self-care plan tailored to individual requirements\n",
            "* Consult healthcare professionals for advice if necessary\n",
            "--------\n",
            "Score: 0.7043\n",
            "### Step 5: Stay Active\n",
            "\n",
            "**Explanation:** Regular exercise is essential for maintaining both physical and mental health. Exercise releases endorphins that boost energy levels, reduce anxiety, and promote better sleep.\n",
            "\n",
            "* **Key Tips:**\n",
            "\t+ Choose exercises that suit your fitness level and preferences, such as yoga, Pilates, dance classes, or bodyweight training routines.\n",
            "\t+ Allocate time for regular walks outside if possible, taking advantage of parks or scenic routes nearby.\n",
            "\t+ Utilize free resources available online, such as workout videos or apps, to guide your routine.\n",
            "\n",
            "### Step 6: Maintain Social Connections\n",
            "\n",
            "**Explanation:** Strong social relationships contribute significantly to emotional well-being. Nurturing connections with friends and family members prevents feelings of isolation and loneliness.\n",
            "--------\n"
          ]
        }
      ],
      "source": [
        "query(\"Give me some tips to improve my mental health.\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 22,
      "id": "e0e9e8dc",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Query: Give me some tips for writing good code.\n",
            "Score: 0.6609\n",
            "Step 6: Improve Code Quality\n",
            "Strive for clean, readable, maintainable code. Adopt consistent naming conventions, indentation styles, and formatting rules. Utilize version control systems like Git to track changes and collaborate effectively. Leverage linters and static analyzers to enforce style guides automatically. Document your work using comments and dedicated documentation tools. High-quality code facilitates collaboration, promotes longevity, and simplifies troubleshooting.\n",
            "\n",
            "Step 7: Embrace Best Practices\n",
            "Follow established best practices relevant to your chosen language and domain. Examples include Object-Oriented Design Principles, SOLID principles, Test-Driven Development (TDD), Dependency Injection, Asynchronous Programming, etc. While seemingly overwhelming initially, integrating them gradually enhances design patterns, scalability, and extensibility. Consult authoritative blogs, books, and articles to stay updated on current trends and recommendations.\n",
            "--------\n",
            "Score: 0.5749\n",
            "Step 4: Work On Real Projects\n",
            "Theory alone won't make you a proficient programmer; hands-on experience does. Apply what you've learned by working on real projects. Begin with small tasks like creating calculators, text-based games, or automating repetitive tasks. Gradually move towards larger projects related to your field of interest. Participate in open-source initiatives, contribute to existing repositories, or develop your application ideas. These experiences enhance problem-solving skills and prepare you for professional challenges.\n",
            "\n",
            "Step 5: Master Debugging Techniques\n",
            "Debugging is inevitable when writing code. Identifying and resolving errors early improves productivity and reduces frustration. Use debuggers provided within IDEs, print statements, or log messages to trace execution flow and pinpoint issues. Familiarize yourself with common error types and causes, especially those specific to your chosen language. Over time, proactive debugging becomes second nature.\n",
            "--------\n",
            "Score: 0.5745\n",
            "Conclusion:\n",
            "Becoming a good programmer requires dedication, persistence, and patience. By methodically progressing through these steps, mastering core concepts, practicing diligently, engaging with peers, and committing to continuous improvement, you'll be well on your way to achieving your goal. Remember, every expert was once a beginner - keep pushing forward!\n",
            "--------\n"
          ]
        }
      ],
      "source": [
        "query(\"Give me some tips for writing good code.\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 23,
      "id": "087fed97",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Query: How to create a basic webpage?\n",
            "Score: 0.5843\n",
            "Title: How to Get a Free Website with Way2Webscape.com\n",
            "\n",
            "Introduction:\n",
            "Way2Webscape.com offers free websites for users who want to create their own online presence without any cost. This tutorial will guide you through the process of getting a free website using this service. By following these steps, you'll be able to create an attractive and functional website that meets your needs.\n",
            "\n",
            "Step 1: Visit Way2Webscape.com\n",
            "Open your web browser and navigate to <https://www.way2webscape.com/>. This will take you to the homepage of Way2Webscape.com.\n",
            "\n",
            "Key tip: Make sure you have a stable internet connection while completing the following steps.\n",
            "\n",
            "Step 2: Click on \"Create Your Free Website\" Button\n",
            "On the top right corner of the homepage, click on the green button labeled \"Create Your Free Website.\" This action will redirect you to the registration page.\n",
            "--------\n",
            "Score: 0.5713\n",
            "Step 6: Choose a Template\n",
            "After logging in, select a template that suits your preferences by browsing through various categories such as business, personal, blog, etc., located on the left sidebar under \"Template Categories\". Once you find a suitable design, hover over it and click on the green \"Use this template\" button below the preview image.\n",
            "\n",
            "Step 7: Customize Your Site\n",
            "You can customize different aspects of your site like its layout, color scheme, background image, font styles, and more via the editor dashboard on the left panel. Remember to save changes made before navigating away from any editing screen.\n",
            "\n",
            "Step 8: Add Pages\n",
            "To add pages to your website, go to the \"Pages\" tab on the editor dashboard. Here, choose between predefined page types (e.g., Home, About Us, Services) or create custom ones according to your requirements. Don't forget to assign appropriate titles and URL slugs to these pages.\n",
            "--------\n",
            "Score: 0.5694\n",
            "Step 9: Edit Page Content\n",
            "For each added page, utilize the content editor to input text, images, videos, links, tables, dividers, or other elements needed. Format texts using headings, bullet points, numbered lists, indentation, alignment, and colors as necessary.\n",
            "\n",
            "Step 10: Configure Settings\n",
            "Navigate to the \"Settings\" tab on the editor dashboard. Fill in essential details about your site including name, description, keywords, contact info, social media profiles, analytics tracking codes, and SEO settings. Save changes once completed.\n",
            "\n",
            "Step 11: Preview Your Site\n",
            "Before publishing your site, preview it first by clicking on the eye icon near the top right corner of the editor interface. Review your entire site carefully, checking for errors or inconsistencies. If satisfied, proceed to the next step; otherwise, make adjustments accordingly.\n",
            "--------\n"
          ]
        }
      ],
      "source": [
        "query(\"How to create a basic webpage?\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 24,
      "id": "e48d2fa4",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Query: What are some environment-friendly practices I can incorporate in everyday life?\n",
            "Score: 0.6947\n",
            "a) Bring reusable bags, containers, utensils, and water bottles when shopping or dining out.\n",
            "b) Purchase items with minimal packaging, prioritize products made from recycled materials, and avoid single-use plastics.\n",
            "c) Participate in composting programs or start composting at home to turn organic waste into nutrient-rich soil amendments.\n",
            "d) Donate unwanted items rather than discarding them, and repurpose household goods when possible.\n",
            "e) Learn about local recycling rules and sort waste accordingly.\n",
            "\n",
            "Key Tip: Familiarize yourself with your city's waste management system to optimize recycling efforts and divert waste from landfills.\n",
            "\n",
            "Step 4: Protect Biodiversity\n",
            "Biodiversity underpins the health and resilience of ecosystems, providing vital services such as pollination, decomposition, pest control, and nutrient cycling. Safeguard biodiversity through the following actions:\n",
            "--------\n",
            "Score: 0.6556\n",
            "a) Use public transportation, carpool, bike, walk, or telecommute whenever possible to minimize fuel consumption.\n",
            "b) If purchasing a vehicle, consider electric or hybrid options that emit fewer greenhouse gases than traditional gasoline-powered cars.\n",
            "c) Improve home energy efficiency through insulation, LED lighting, Energy Star appliances, and renewable energy sources like solar panels.\n",
            "d) Limit air travel and opt for video conferencing when feasible.\n",
            "e) Be mindful of your dietary choices – consume less red meat, choose locally sourced foods, and reduce food waste.\n",
            "f) Plant trees and support reforestation projects as they absorb CO2 from the atmosphere.\n",
            "g) Advocate for policies that promote clean energy and reduced emissions at local, national, and international levels.\n",
            "\n",
            "Key Tip: Calculate your carbon footprint using online tools (such as the EPA's Household Carbon Footprint Calculator) to identify areas where you can make improvements.\n",
            "--------\n",
            "Score: 0.6265\n",
            "a) Host workshops, film screenings, or community events focused on sustainability topics.\n",
            "b) Engage with elected officials and voice concerns regarding environmental issues.\n",
            "c) Collaborate with schools, libraries, and nonprofit organizations to develop educational programming related to conservation and sustainability.\n",
            "d) Leverage social media platforms to disseminate information and inspire action among friends, family, and followers.\n",
            "\n",
            "Key Tip: Encouraging just one person to adopt more eco-friendly habits can create a ripple effect leading to broader positive change.\n",
            "\n",
            "Conclusion:\n",
            "Saving our environment requires collective effort and commitment from individuals, businesses, and governments worldwide. While addressing global challenges like climate change may seem daunting, taking concrete steps toward sustainability at the personal level contributes meaningfully to larger-scale progress. Together, we can foster a greener, healthier, and more equitable world for all living beings.\n",
            "--------\n"
          ]
        }
      ],
      "source": [
        "query(\n",
        "    \"What are some environment-friendly practices I can incorporate in everyday life?\"\n",
        ")"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "conda_python3",
      "language": "python",
      "name": "conda_python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.18"
    },
    "widgets": {
      "application/vnd.jupyter.widget-state+json": {
        "state": {}
      }
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
